<template>
  <div class="login">
    <div class="container">
      <div class="row">
        <div class="col-md-8 m-auto">
          <h1 class="display-4 text-center">登录</h1>
          <p class="lead text-center">使用已有的账户登录</p>
          <form @submit.prevent="submit" autocomplete="off" method="post ">
            <TextFiled
              name="email"
              placeholder="请输入邮箱"
              type="email"
              v-model="user.email"
              :error="error.email"
            />
            <TextFiled
              name="password"
              placeholder="请输入密码"
              type="password"
              v-model="user.password"
              :error="error.password"
            />
            <input type="submit" class="btn btn-info btn-block mt-4">
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
import jwt_decode from "jwt-decode";
import TextFiled from "./common/TextFiled";
export default {
  data() {
    return {
      user: {
        email: "",
        password: ""
      },
      error: {}
    };
  },
  components: {
    TextFiled
  },
  methods: {
    submit() {
      //   console.log(this.user.email);
      this.$axios
        .post("http://localhost:5000/api/users/login", this.user)
        .then(res => {
          // console.log(res.data);
          const { token } = res.data;

          //存储token
          window.localStorage.setItem("jwt", token);

          //解析token
          const decode = jwt_decode(token);
          this.error = {};
          // console.log(decode);
          //调用action改变user和 用户状态
          this.$store.dispatch("setIsAuthenticated", true);
          this.$store.dispatch("setUser", decode);

          //页面跳转
          this.$router.push("/dashboard");
        })
        .catch(err => {
          if (err.response.data) {
            this.error = err.response.data;
          }
        });
      // }
    }
  },
  beforeRouteEnter(to, from, next) {
    // ...
    next(vm => {
      vm.error = {};
    });
  }
};
</script>

<style scoped lang="stylus">
</style>
